<!-- AMapContainer.vue -->
<template>
  <div id="mapContainer" ref="mapContainer" style="width: 100%; height: 100vh;"></div>
  <MapControls :AMap="AMap" :map="map"></MapControls>
  <div id="panel"></div>
</template>

<script setup>
import { ref, shallowRef, onMounted, onUnmounted } from 'vue';
import { createApp } from 'vue'; // 引入 createApp
import AMapLoader from '@amap/amap-jsapi-loader';
import CustomInfoWindow from './CustomInfoWindow.vue';
import MapControls from "./MapControls.vue";
import axios from "axios"; // 引入你的自定义弹窗组件
const mapContainer = ref(null);
// 地图实例和信息窗体实例
const map = ref(null);
let local = null;
const AMap = ref(null);
const infoWindow = shallowRef(null);

// 接收父组件传递的配置和标记点数据
const props = defineProps({
  mapKey: String,
  securityJsCode: String,
  center: {
    type: Array,
    default: () => [116.397428, 39.90923]
  },
  zoom: {
    type: Number,
    default: 11
  },
  markers: Array // 格式: { position: [lng, lat], title: '', content: '', ...自定义属性 }
});

// 初始化地图
onMounted(() => {
  initMap();
});

onUnmounted(() => {
  map.value?.destroy();
});

const initMap = async () => {
  window._AMapSecurityConfig = {
    securityJsCode: props.securityJsCode
  };

  try {
    AMap.value = await AMapLoader.load({
      key: props.mapKey,
      version: '2.0',
      plugins: ['AMap.InfoWindow', 'AMap.ControlBar','AMap.ToolBar','AMap.PolylineEditor','AMap.MoveAnimation'],
      //加载 AMapUI
      AMapUI: {
        version: "1.1", // AMapUI 版本
      },
      keyboardEnable: true, //
      // 动画效果 高德API加载
      Loca:{                // 是否加载 Loca， 缺省不加载
        version: '2.0.0'  // Loca 版本，缺省 1.3.2
      },
    });

   map.value = new  AMap.value.Map('mapContainer', {
     zoom: 5.29,
     // showLabel: false,
     viewMode: '3D',
     pitch: 48,
     center: [104.780269, 34.955403],
     mapStyle: 'amap://styles/grey',
     showBuildingBlock: false,
     showLabel: false,
    });

    // 关键：初始化Loca容器
    local = new Loca.Container({
      map: map.value,
    });

    // console.log(loca.value,'loca.value')

    const controlBar = new AMap.value.ControlBar({
      position:{
        right:'10px',
        top:'10px'
      }
    });
    controlBar.addTo(map.value);

    const toolBar = new AMap.value.ToolBar({
      position:{
        right:'40px',
        top:'110px'
      }
    });
    toolBar.addTo(map.value);
    // beijingLineAnimate();

    const dom = threeDMap();

    map.value.on('complete',()=>{
      dom.show(1000)
    })

  } catch (error) {
    console.error('地图加载失败:', error);
  }
};

const threeDMap = () => {
  const loca = local;

  // 光源处理
  loca.ambLight = {
    intensity: 0.7,
    color: '#7b7bff',
  };
  loca.dirLight = {
    intensity: 0.8,
    color: '#fff',
    target: [0, 0, 0],
    position: [0, -1, 1],
  };
  loca.pointLight = {
    color: 'rgb(240,88,25)',
    position: [112.028276, 31.58538, 2000000],
    intensity: 3,
    // 距离表示从光源到光照强度为 0 的位置，0 就是光不会消失。
    distance: 5000000,
  };
  var pl = new Loca.PrismLayer({
    zIndex: 10,
    opacity: 1,
    visible: false,
    hasSide: true,
  });

  var geo = new Loca.GeoJSONSource({
    url: 'https://a.amap.com/Loca/static/loca-v2/demos/mock_data/gdp.json',
  });
  pl.setSource(geo);
  // top3 的城市增加文字
  var topConf = {
    '上海市': 'https://a.amap.com/Loca/static/loca-v2/demos/images/top-one.png',
    '北京市': 'https://a.amap.com/Loca/static/loca-v2/demos/images/top-two.png',
    '广州市': 'https://a.amap.com/Loca/static/loca-v2/demos/images/top-three.png',
  };
  pl.setStyle({
    unit: 'meter',
    sideNumber: 4,
    topColor: (index, f) => {
      var n = f.properties['GDP'];
      return n > 7000 ? '#E97091' : '#2852F1';
    },
    sideTopColor: (index, f) => {
      var n = f.properties['GDP'];
      return n > 7000 ? '#E97091' : '#2852F1';
    },
    sideBottomColor: '#002bb9',
    radius: 15000,
    height: (index, f) => {
      var props = f.properties;
      var height = Math.max(100, Math.sqrt(props['GDP']) * 9000 - 50000);
      var conf = topConf[props['名称']];
      // top3 的数据，增加文字表达
      if (conf) {
        map.value.add(
          new AMap.value.Marker({
            anchor: 'bottom-center',
            position: [f.coordinates[0], f.coordinates[1], height],
            content: '<div style="margin-bottom: 10px; float: left; font-size: 14px;height: 57px; width: 180px; color:#fff; background: no-repeat url(' +
              conf +
              '); background-size: 100%;"><p style="margin: 7px 0 0 35px; height: 20px; line-height:20px;">' +
              props['名称'] + '人口 ' + props['人口'] + '</p>' +
              '<p style="margin: 4px 0 0 35px; height: 20px; line-height:20px; color: #00a9ff; font-size: 13px;">' +
              props['GDP'] + ' 元' +
              '</p></div>',
          }),
        );
      }
      return height;
    },
    rotation: 360,
    altitude: 0,
  });
  loca.add(pl);


  return pl;
}

const beijingLineAnimate = ()=>{
  // 添加点位图层
  const scatter = new Loca.ScatterLayer({
    loca: local,
    zIndex: 10,
    opacity: 0.7,
    visible: true,
    zooms: [2, 20],
  });

  const pointGeoJson = new Loca.GeoJSONSource({
    url: 'https://a.amap.com/Loca/static/loca-v2/demos/mock_data/pulselink-china-city-point.json',
  });
  scatter.setSource(pointGeoJson);

  scatter.setStyle({
    unit: 'meter',
    size: [100000, 100000],
    borderWidth: 0,
    texture: 'https://a.amap.com/Loca/static/loca-v2/demos/images/breath_red.png',
    duration: 2000,
    animate: true,
  });

  local.add(scatter);

  const pulseLink = new Loca.PulseLinkLayer({
    loca: local,
    zIndex: 10,
    opacity: 1,
    visible: true,
    zooms: [2, 22],
    depth: true,
  });

  const geo = new Loca.GeoJSONSource({
    url: 'https://a.amap.com/Loca/static/loca-v2/demos/mock_data/data-line-out.json',
  });

  pulseLink.setSource(geo);
  pulseLink.setStyle({
    unit: 'meter',
    dash: [40000, 0, 40000, 0],
    lineWidth: function () {
      return [20000, 1000];
    },
    height: function (index, feat) {
      return feat.distance / 3 + 10;
    },
    // altitude: 1000,
    smoothSteps: 30,
    speed: function (index, prop) {
      return 1000 + Math.random() * 200000;
    },
    flowLength: 100000,
    lineColors: function (index, feat) {
      return ['rgb(255,228,105)', 'rgb(255,164,105)', 'rgba(1, 34, 249,1)'];
    },
    maxHeightScale: 0.3, // 弧顶位置比例
    headColor: 'rgba(255, 255, 0, 1)',
    trailColor: 'rgba(255, 255,0,0)',
  });

  local.add(pulseLink);
  console.log(pulseLink.setStyle,'styles')
  const dat = new Loca.Dat();
  dat.addLayer(pulseLink)
}

// 暴露方法给父组件，例如允许父组件主动关闭弹窗
defineExpose({
  closeWindow: () => infoWindow.value?.close()
});
</script>

<style scoped>
#mapContainer {
  width: 100vw;
  height: 100vh;
}

#panel {
  position: absolute;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 10px;
  right: 10px;
  width: 280px;
}
</style>